import { h, Fragment } from "preact";
import { useEffect } from "preact/hooks";
import { Handlers, PageProps } from "$fresh/server.ts";
import { getDbClient } from "../../utils/db.ts";
import HeadComponent from "../../components/Head.tsx";
import Container from "../../components/Container.tsx";
import Card from "../../components/Card.tsx";
import Button from "../../components/Button.tsx";

interface Post {
  id: number;
  title: string;
  content: string;
  created_at: string;
}

export const handler: Handlers<Post | null> = {
  async GET(req, ctx) {
    const id = ctx.params.id;
    let client;
    try {
      client = await getDbClient();
      const result = await client.query(
        "SELECT id, title, content, created_at FROM posts WHERE id = ?",
        [id]
      );
      if (result.length === 0) {
        return ctx.render(null);
      }
      return ctx.render(result[0] as Post);
    } catch (error) {
      console.error("Error fetching post:", error);
      return ctx.render(null);
    } finally {
      if (client) await client.close();
    }
  },
};

export default function PostPage({ data, state }: PageProps<Post | null>) {
  const post = data;
  const isAdmin = state.isAdmin as boolean || false;
  const adminNickname = state.adminNickname as string || '管理员';
  const adminAvatarUrl = state.adminAvatarUrl as string | null;

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric',
      month: '2-digit', 
      day: '2-digit'
    });
  };

  // 在组件挂载后，为body添加类以允许滚动
  useEffect(() => {
    // 添加可滚动类
    document.body.classList.add('article-page-scrollable');
    
    // 组件卸载时移除类
    return () => {
      document.body.classList.remove('article-page-scrollable');
    };
  }, []);

  if (!post) {
    return (
      <>
        <HeadComponent title="未找到文章" description="文章未找到">
          {/* 引入专用的文章页面样式 */}
          <link rel="stylesheet" href="/article-styles.css" />
          <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600&display=swap" rel="stylesheet" />
          {/* REMOVED Inline body styles, now handled by article-styles.css */}
          <script dangerouslySetInnerHTML={{__html: `
            // 立即执行以确保滚动效果
            document.body.classList.add('article-page-body');
            document.body.classList.add('enable-scroll');
            document.body.style.overflow = 'auto';
            document.body.style.maxHeight = 'none';
            document.body.style.height = 'auto';
            
            // 确保DOM加载后也添加类和样式
            document.addEventListener('DOMContentLoaded', function() {
              document.body.classList.add('article-page-body');
              document.body.classList.add('enable-scroll');
              document.body.style.overflow = 'auto';
              document.body.style.maxHeight = 'none';
              document.body.style.height = 'auto';
            });
          `}} />
        </HeadComponent>
        <div class="article-container flex flex-col min-h-screen"> {/* Ensure min-h-screen is on the main container if not on body */}
          {/* 顶部导航 */}
          <header class="article-header-glass py-4 px-4 md:px-0"> {/* ADDED article-header-glass, REMOVED other bg/border/shadow */}
            <div class="container mx-auto max-w-3xl flex items-center justify-between">
              <a href="/" class="flex items-center space-x-2 text-gray-800 hover:text-blue-600 transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                <span class="text-sm font-medium">返回首页</span>
              </a>
              {/* Admin Info & Logout Link for "Not Found" page header */}
              {isAdmin && adminNickname && (
                <div class="flex items-center gap-3">
                  {adminAvatarUrl && adminAvatarUrl.trim() !== "" ? (
                    <img src={adminAvatarUrl} alt={adminNickname} class="w-7 h-7 rounded-full object-cover border border-gray-300 shadow-sm" />
                  ) : (
                    <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 border border-slate-300 shadow-sm">
                      {adminNickname.charAt(0).toUpperCase()}
                    </div>
                  )}
                  <a href="/api/auth/logout" class="text-sm text-gray-700 font-medium hover:text-blue-700 hover:underline cursor-pointer" title="点击退出登录">
                    你好, {adminNickname}
                  </a>
                </div>
              )}
              {isAdmin && !adminNickname && ( // Fallback for generic admin display
                <div class="flex items-center gap-3">
                  <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-gray-500 border border-slate-300 shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                      <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                    </svg>
                  </div>
                  <a href="/api/auth/logout" class="text-xs text-blue-600 hover:text-blue-800 hover:underline">退出登录</a>
                </div>
              )}
            </div>
          </header>
          
          <main class="flex-grow flex items-center justify-center py-16 px-4 md:px-0 animate-enter"> {/* ADDED animate-enter */}
            <div class="text-center max-w-md">
              <div class="mb-8">
                <div class="text-gray-300 text-7xl mb-4">😕</div>
                <h1 class="text-3xl font-bold text-gray-800 mb-2">未找到文章</h1>
                <p class="text-gray-500 mb-8">
                  抱歉，无法找到您请求的文章。它可能已被删除或者从未存在过。
                </p>
                <a 
                  href="/"
                  class="inline-flex items-center justify-center px-5 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors font-medium"
                >
                  返回首页
                </a>
              </div>
            </div>
          </main>
          
          <footer class="article-footer-glass py-8"> {/* ADDED article-footer-glass, REMOVED other bg/border */}
            <div class="container mx-auto max-w-3xl px-4 md:px-0">
              <p class="text-sm text-gray-500 text-center">
                © {new Date().getFullYear()} MiniBlog. 保留所有权利。
              </p>
            </div>
          </footer>
        </div>
      </>
    );
  }

  return (
    <>
      <HeadComponent 
        title={post.title} 
        description={post.content.substring(0, 150)} 
      >
        {/* 引入专用的文章页面样式 */}
        <link rel="stylesheet" href="/article-styles.css" />
        <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
        {/* REMOVED Inline body styles, now handled by article-styles.css */}
        <style>{`
          /* Minimal essential inline styles if any, otherwise this can be removed if all handled by article-styles */
          /* For example, if a specific font for JUST this page's body is absolutely needed and not in article-styles */
          /* body { font-family: 'SpecificPageFont', sans-serif !important; } */

          /* Keeping article content specific typography overrides for now, might move to CSS file later */
          .article-content h1, .article-content h2, .article-content h3 {
            font-family: 'Noto Serif SC', serif !important;
            color: #1f2937 !important; /* 标题颜色 */
          }
          .article-content p, .article-content li {
            font-family: 'Noto Serif SC', serif !important;
            color: #4b5563 !important; /* 段落文本颜色 */
            line-height: 1.85 !important;
          }
          .article-content a {
            color: #2563eb !important; /* 链接颜色 */
            text-decoration: none !important;
          }
          .article-content a:hover {
            text-decoration: underline !important;
          }
        `}</style>
        <script dangerouslySetInnerHTML={{__html: `
          document.addEventListener('DOMContentLoaded', function() {
            document.body.style.overflow = 'auto';
            document.body.style.maxHeight = 'none';
            document.body.style.height = 'auto';
          });
        `}} />
      </HeadComponent>
      
      <div class="article-container flex flex-col min-h-screen"> {/* Ensured min-h-screen for main container */}
        {/* 顶部导航 - 返回首页 */}
        <header class="article-header-glass sticky top-0 z-50"> {/* ADDED article-header-glass, REMOVED other bg/shadow/border */}
          <div class="container mx-auto max-w-3xl py-3 px-4 md:px-0 flex items-center justify-between">
            <a href="/" class="flex items-center space-x-2 text-gray-600 hover:text-blue-600 transition-colors duration-200">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              <span class="text-sm font-medium">返回首页</span>
            </a>
            
            {/* Admin Info & Logout Link for actual post page header */}
            {isAdmin && adminNickname && (
              <div class="flex items-center gap-3">
                {adminAvatarUrl && adminAvatarUrl.trim() !== "" ? (
                  <img src={adminAvatarUrl} alt={adminNickname} class="w-7 h-7 rounded-full object-cover border border-gray-300 shadow-sm" />
                ) : (
                  <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 border border-slate-300 shadow-sm">
                    {adminNickname.charAt(0).toUpperCase()}
                  </div>
                )}
                <a href="/api/auth/logout" class="text-sm text-gray-700 font-medium hover:text-blue-700 hover:underline cursor-pointer" title="点击退出登录">
                  你好, {adminNickname}
                </a>
              </div>
            )}
            {isAdmin && !adminNickname && ( // Fallback for generic admin display
              <div class="flex items-center gap-3">
                <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-gray-500 border border-slate-300 shadow-sm">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                  </svg>
                </div>
                <a href="/api/auth/logout" class="text-xs text-blue-600 hover:text-blue-800 hover:underline">退出登录</a>
            </div>
            )}

            {!isAdmin && (
              <div class="text-xs text-gray-400">
                 发布于: {formatDate(post.created_at)}
              </div>
            )}
          </div>
        </header>
        
        <main class="flex-grow py-10 md:py-12 px-4 md:px-0 article-content animate-enter"> {/* ADDED animate-enter */}
          <div class="container mx-auto max-w-3xl bg-white p-6 md:p-10 rounded-lg shadow-subtle">
            {/* 文章标题 */}
            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-4 leading-tight">
              {post.title}
            </h1>
            
            {/* 文章信息 - 标签 */}
            <div class="flex items-center text-xs text-gray-500 mb-8">
              <span class="inline-block bg-blue-50 text-blue-700 rounded-full px-3 py-1 font-medium border border-blue-200">
                MiniBlog
              </span>
            </div>
          
          {/* 文章内容 */}
            <article class="prose prose-lg max-w-none leading-relaxed">
              <div dangerouslySetInnerHTML={{ __html: post.content }}></div>
            </article>
          
            {/* 文章页脚操作 */}
            <div class="mt-10 md:mt-12 pt-6 md:pt-8 border-t border-gray-200/80">
              <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
                <a href="/" class="btn-outline-subtle group">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5 group-hover:animate-pulse-once" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M7 16l-4-4m0 0l4-4m-4 4h18" />
                </svg>
                  查看更多文章
                </a>
              
          {isAdmin && (
                <div class="flex gap-3">
                    <a 
                      href={`/admin/posts/${post.id}/edit`}
                      class="btn-secondary-subtle"
                  >
                    编辑文章
                    </a>
                    <form 
                      method="POST" 
                      action="/api/posts/delete" 
                      onSubmit={(e) => { if (!confirm('确定要删除这篇文章吗？')) e.preventDefault(); }}
                      class="inline"
                    >
                      <input type="hidden" name="post_id" value={post.id} />
                      <button
                        type="submit"
                        class="btn-danger-subtle"
                  >
                    删除文章
                      </button>
                    </form>
            </div>
          )}
        </div>
            
            {/* 分享区域 */}
              <div class="mt-8 md:mt-10 pt-6 border-t border-gray-200/80">
                <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">分享这篇文章</h3>
                <div class="flex gap-3">
                  {[ 
                    { name: 'Twitter', icon: '<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.713v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84"></path></svg>', action: 'shareOnTwitter' },
                    { name: 'Facebook', icon: '<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" clip-rule="evenodd"></path></svg>', action: 'shareOnFacebook' },
                    { name: 'Email', icon: '<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z"></path><path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z"></path></svg>', action: 'shareByEmail' }
                  ].map(share => (
                    <a 
                      key={share.name}
                      data-share={share.name.toLowerCase()} 
                      class="share-btn"
                      aria-label={`在${share.name}上分享`}
                      onClick={(e) => { e.preventDefault(); window[share.action](); }}
                      dangerouslySetInnerHTML={{ __html: share.icon }}
                    >
                </a>
                  ))}
                </div>
                <script dangerouslySetInnerHTML={{__html: `
                  window.shareOnTwitter = function() { const url = window.location.href; window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(document.title) + '&url=' + encodeURIComponent(url), '_blank'); };
                  window.shareOnFacebook = function() { const url = window.location.href; window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url), '_blank'); };
                  window.shareByEmail = function() { const url = window.location.href; window.location.href = 'mailto:?subject=' + encodeURIComponent(document.title) + '&body=' + encodeURIComponent(url); };
                `}} />
              </div>
            </div>
          </div>
        </main>
        
        <footer class="article-footer-glass py-8 mt-auto"> {/* ADDED article-footer-glass, REMOVED other bg/border */}
          <div class="container mx-auto max-w-3xl px-4 md:px-0">
            <p class="text-xs text-gray-500 text-center">
              © {new Date().getFullYear()} MiniBlog. 保留所有权利。
            </p>
            </div>
          </footer>
      </div>
    </>
  );
}